import React, { Component } from 'react';
import { messages } from 'share/common';
import Edit from '../svg-component/edit';
import 'styles/expense/expense-header.scss';
import errorMessage from 'share/errorMessage';
import ExpenseService from '../expense-service';
import UpDown from '../business-component/up-down';
import Annotate from 'components/template/annotate';
import TemplateHoc from '../component/template-hoc';
import { Icon, message, Popover, Spin } from 'antd';
import shallowEqual from '../component/shallowEqual';
import noImage from 'images/expense-detail/no-image.svg';
import autoAuditService from '../../finance-setting/auto-audit/auto-audit.service';
import { connect } from 'react-redux';

@connect(mapStateToProps)
@TemplateHoc
class ExpenseHeader extends Component {

  static contextTypes = {
    nowExpenseDataSource: React.PropTypes.array,
    annotates: React.PropTypes.array,
    isAuditEditable: React.PropTypes.bool,
    isWaitForAudit: React.PropTypes.bool,
    currentExpense: React.PropTypes.object,
    expenseReport: React.PropTypes.object,
    currentExpenseType: React.PropTypes.object,
    currentExpenseIndex: React.PropTypes.number,
    headerData: React.PropTypes.object,
    jobInfo: React.PropTypes.object
  };

  static propTypes = {};


  constructor(props, context) {
    super(props, context);
    this.state = {
      ...ExpenseHeader.initState(context)
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState)
  }

  componentWillReceiveProps(nextProps, nextContext) {
   nextProps.randomHash !== this.props.randomHash && this.setState({ ...ExpenseHeader.initState(nextContext) });
  }

   static initState(context) {
    const { currentExpense: { manualAudit }, annotates} = context;
    return {
      annotates,
      manualAudit,
      manualAuditLoading: false,
    };
  }

  handleOnChange = async () => {
    const { manualAudit } = this.state;
    const { currentExpense: { invoiceOID }, expenseReport: { expenseReportOID } } = this.context;
    this.setState({ manualAuditLoading: true });
    let params = { invoiceOIDs: [invoiceOID], expenseReportOID, manualAudit: !manualAudit };
    try {
      await autoAuditService.setManualAudit(params);
      message.success(messages('common.operate.success')/*操作成功*/);
      this.setState({ manualAudit: !manualAudit });
      this.props.refreshApprovedKeys(invoiceOID, !manualAudit);
    } catch (e) {
      errorMessage(e.response);
    }
    this.setState({ manualAuditLoading: false });
  };

  handleDisabled = (index) => {
    const { nowExpenseDataSource, currentExpenseIndex } = this.context;
    return (index === 'up' && currentExpenseIndex === 0) || (index === 'down' && currentExpenseIndex === nowExpenseDataSource.length - 1);
  };

  handleAnnotate = async () => {
    const { currentExpense: { invoiceOID } } = this.context;
    const annotates = await ExpenseService.getAnnotate(invoiceOID);
    this.setState({ annotates });
  };

  render() {
    const { loginUser } = this.props;
    const { manualAuditLoading, manualAudit, annotates } = this.state;
    const { headerData: { id, fullName, expenseTypeName, expenseTypeIconURL, createdDate }, isAuditEditable, isWaitForAudit } = this.context;
    return (
      <section className="expense-header">
        <div className="expense-header-left" onClick={this.props.close}><Icon type="left"/></div>
        <div className="expense-header-content">
          <div className="expense-header-content-creator">
            <div>{fullName} {createdDate}</div>
            <div className="expense-header-audit-func">
              {
                isWaitForAudit &&
                <div className="expense-header-icon">
                  <Spin spinning={manualAuditLoading}>
                    <div
                      onClick={this.handleOnChange}
                      className={`expense-header-audit-pending ${manualAudit ? 'expense-header-audit-audited' : ''}`}
                    >
                      {manualAudit ? messages('expense-1.key693')/*已审核*/ : messages('expense-1.key694')/*待审核*/}
                    </div>
                  </Spin>
                </div>
              }
              {
                isAuditEditable && (
                  <div className="expense-header-audit-edit expense-header-icon" onClick={() => this.props.handleUtil('edit')}>
                    <Edit/>{messages('common.edit')/*编辑*/}
                  </div>)
              }
              <UpDown
                handleDisabled={this.handleDisabled}
                handleUtil={this.props.handleUtil}
              />
            </div>
          </div>
          <Annotate
            params={{
              typeName: 'INVOICE',
              entityID: id,
              target: { type: 'expenseType' }
            }}
            disabled={!isWaitForAudit}
            annotateList={ExpenseService.getAnnotateList('expenseType', annotates, loginUser)}
            onChange={this.handleAnnotate}
          >
            <div className={`expense-header-content-title ${isWaitForAudit ? 'expense-item-annotate' : ''}`}>
              <img className="expense-header-content-icon" src={expenseTypeIconURL || noImage} alt="icon"/>
              <Popover placement={'bottomLeft'} content={expenseTypeName}>
                <span className="expense-header-content-title-desc">{expenseTypeName}</span>
              </Popover>
            </div>
          </Annotate>
        </div>
      </section>
    );
  }
}


function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser
  };
}

ExpenseHeader.propTypes = {};
export default ExpenseHeader;

